import React, { useEffect, useMemo, useRef } from 'react';
import { Chart } from '@antv/g2';

const generateData = () => {
  const times = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
  const types = ['门1', '门2', '门3'];

  return times.flatMap(time =>
    types.map(type => ({
      time,
      type,
      value: Math.floor(Math.random() * 100 + 150),
    }))
  );
};

const data = generateData();

const EventTrendChart: React.FC<{ eventTrend: any }> = ({ eventTrend = [] }) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const chartRef = useRef<Chart | null>(null);

  const data = useMemo(() => {
    const list: any[] = []

    eventTrend?.forEach((item: any) => {

      list.push({
        时间: item.weekDay,
        数值: item.level1,
        type: '等级1'
      })

      list.push({
        时间: item.weekDay,
        数值: item.level2,
        type: '等级2'
      })

      list.push({
        时间: item.weekDay,
        数值: item.level3,
        type: '等级3'
      })

      list.push({
        时间: item.weekDay,
        数值: item.level4,
        type: '等级4'
      })
    })

    return list
  }, [eventTrend])
  
  useEffect(() => {
    const renderChart = () => {
      if (containerRef.current) {
        if (chartRef.current) {
          chartRef.current.destroy();
        }


        const chart = new Chart({
          container: containerRef.current,
          autoFit: true,
          theme: 'dark',
          // paddingRight: 120,
        });

        chart
          .interval()
          .data(data)
          .encode('x', '时间')
          .encode('y', '数值')
          .encode('color', 'type')
          .transform({ type: 'dodgeX' })
          .interaction('elementHighlight', { background: true });

        chart.render();

        chartRef.current = chart;
      }
    };

    renderChart();

    const resizeObserver = new ResizeObserver(() => {
      renderChart();
    });

    if (containerRef.current) {
      resizeObserver.observe(containerRef.current);
    }

    return () => {
      resizeObserver.disconnect();
      if (chartRef.current) {
        chartRef.current.destroy();
      }
    };
  }, [data]);

  return <div ref={containerRef} className="chart-container" />;
};

export default EventTrendChart;
